import React, { Component } from 'react';
import { message } from 'antd';
import LoginForm from './components/LoginForm/index.jsx';
import { login } from './api.js';
import './index.less';

const loginStatusText = {
  success: '登录成功',
  multiTenant: '登录时需要传入租户代码',
  captchaError: "验证码错误",
  frozen: "账号被冻结",
  locked: "账号被锁定",
  failure: "账号密码错误或账号不存在",
  default: '登录错误'

};

export default class Login extends Component {
  state = {
    loading: false,
    errorMsg: ''
  }

  login = (params) => {
    this.setState({ loading: true });

    login(params).then(res => {
      const { success, data} = res || {};
      if(success && data){
        const { loginStatus = "default" } = data;
        if (loginStatus === "success") {
          localStorage.setItem('Authorization', JSON.stringify(data));
          localStorage.setItem('_s', res.sessionId);
          setTimeout(() => {
            this.props.history.push({pathname: '/navigationMenu', state: params})
          }, 200);// 延迟进入
        } else {
          const errorMsg = loginStatusText[loginStatus];
          if (loginStatus === "multiTenant") {
            this.setState({
              errorMsg,
              showTenant: true,
            });
          }

          message.error(errorMsg);
        }
      }else {
        message.error("登录失败");
      }
    })
    .finally(() => {
      this.setState({loading: false});
    })
  }

  render() {
    const { errorMsg, loading, showTenant } = this.state;

    return (
      <div className="login-page" onKeyPress={e => {
        if (e.which === 13 && e.target.type === 'password') {
          this.LoginForm.login();
        }
      }}>
        <div className="login-header">
          <div className="logo">
            SEI管理系统
          </div>
        </div>
        <div className="login-content-wrap">
          <div className="login-content">
            <div className="word"></div>
            <div className="login-box">
              <div className="title">账号登录</div>
              <LoginForm wrappedComponentRef={inst => { this.LoginForm = inst; }} onLogin={this.login} errorMsg={errorMsg} loading={loading} showTenant={showTenant}/>
            </div>
          </div>
        </div>
        <footer>
          <span>Copyright ©️ 2018 zp Inc. All rights reserved.京ICP备12039470号</span>
        </footer>
      </div>
    );
  }
}
